package org.baicaixiaozhan.emailmanager.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.GsonBuilder;
import io.jsonwebtoken.Jwts;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.baicaixiaozhan.emailmanager.util.ResultTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.crypto.SecretKey;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.Date;

/**
 * DESC:
 *
 * @author : baicaixiaozhan
 * @since : 2021-06-20
 */
@AllArgsConstructor
public class JwtUsernameAndPasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final AuthenticationManager authenticationManager;
    private final JwtConfig jwtConfig;
    private final SecretKey secretKey;

    @SneakyThrows({AuthenticationException.class, IOException.class})
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {

            final UsernameAndPasswordAuthenticationRequest authenticationRequest = new ObjectMapper()
                    .readValue(request.getInputStream(), UsernameAndPasswordAuthenticationRequest.class);
            final UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername()
                    , authenticationRequest.getPassword());

            return authenticationManager.authenticate(authenticationToken);
    }

    /**
     * when {@link JwtUsernameAndPasswordAuthenticationFilter#attemptAuthentication(HttpServletRequest, HttpServletResponse)}
     * successful, do this sends token to client
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void successfulAuthentication(HttpServletRequest request,
                                         HttpServletResponse response,
                                         FilterChain chain,
                                         Authentication authResult) throws IOException, ServletException {
        final String authorities = Jwts.builder()
                .setSubject(authResult.getName())
                .claim("authorities", authResult.getAuthorities())
                .setIssuedAt(new Date())
                .setExpiration(java.sql.Date.valueOf(LocalDate.now().plusWeeks(2)))
                .signWith(secretKey)
                .compact();

        response.setHeader("authorization", jwtConfig.getTokenPrefix() + authorities);
        PrintWriter writer = response.getWriter();
        writer.write(new GsonBuilder().serializeNulls().create().toJson(ResultTemplate.ok()));
        writer.flush();
    }

    /**
     * when {@link JwtUsernameAndPasswordAuthenticationFilter#attemptAuthentication(HttpServletRequest, HttpServletResponse)}
     * unsuccessful, do this sends error message to client
     *
     * @param request
     * @param response
     * @param failed
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException failed) throws IOException, ServletException {
        PrintWriter writer = response.getWriter();
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        writer.write(new GsonBuilder().serializeNulls().create().toJson(ResultTemplate.badRequest("用户名或者密码有误")));
        writer.flush();
    }
}
